package com.etc.util;

import java.util.HashMap;
import java.util.Map;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.etc.controller.DeptController;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTPayload;
import cn.hutool.jwt.JWTUtil;

/**
 * 
 * @ClassName: MyJWTHutool
 * @Description: MyJWTHutool 生成token,解析token,验证token
 * @author knowno
 * @date 2022年4月11日 下午2:09:08
 *
 */
public class MyJWTHutool {
	// 自己定义日志对象,在程序中记录日志
	// org.apache.logging.log4j.Logger; 接口
	// org.apache.logging.log4j.LogManager 日志管理器

	static Logger logger = LogManager.getLogger(DeptController.class);

	private MyJWTHutool() {
		// TODO Auto-generated constructor stub
	}

	/**
	 * 生成token
	 * 
	 * @param userid
	 * @param username
	 * @return
	 */
	public static String createToken(int userid, String username) {

		DateTime now = DateTime.now();
		DateTime newTime = now.offsetNew(DateField.MINUTE, 5);

		Map<String, Object> payload = new HashMap<String, Object>();
		// 签发时间
		payload.put(JWTPayload.ISSUED_AT, now);
		// 过期时间
		payload.put(JWTPayload.EXPIRES_AT, newTime);
		// 生效时间
		payload.put(JWTPayload.NOT_BEFORE, now);
		// 载荷
		payload.put("userid", userid);
		payload.put("username", username);

		String key = "jjwt";

		String token = JWTUtil.createToken(payload, key.getBytes());

		logger.info("createToken token :" + token);

		return token;

	}

	/**
	 * 解析token的方法
	 * 
	 * @param token
	 * @return
	 */
	public static boolean parseToken(String token) {

		JWT jwt = JWTUtil.parseToken(token);
		
		String key = "jjwt";
		boolean verifyKey = jwt.setKey(key.getBytes()).verify();
		logger.info("parseToken verifyKey: "+verifyKey);

		boolean flag = jwt.validate(0);
		logger.info("parseToken flag :" + flag);
		
		return flag;
	}

	/**
	 * 返回token过期时间
	 * 
	 * @param token
	 * @return
	 */
	public static long getExpTime(String token) {

		final JWT jwt = JWTUtil.parseToken(token);
		return (long) jwt.getPayload("expire_time") - System.currentTimeMillis();
	}

	/**
	 * 返回username
	 * 
	 * @param token
	 * @return
	 */
	public static String getusername(String token) {
		String username = null;
		try {
			final JWT jwt = JWTUtil.parseToken(token);
			username = (String) jwt.getPayload("username");
		} catch (Exception e) {
			System.out.println("解析异常");
		}

		return username;
	}
}
